<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Chumper\Zipper\Zipper;
use App\Models\CabinetDataSecondBackup;
use Swoole\Timer;

class MonthBackup extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'month-backup';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command. 
     *
     * @return mixed
     */
    public function handle()
    {
        $interspace = 60 * 60 * 24 * 1000;  //一天

        Timer::tick($interspace, function (int $timer_id) {
            $this->doBackup();
        });
        \Swoole\Event::wait();
        return;
    }

    public function doBackup()
    {
        $thisMonth = date("Y-m");

        $folderName = date('Ym', strtotime("$thisMonth -1 month"));
        $targetFolder = '/filebakup/yun/';
        $folder = $targetFolder.$folderName;
        $targetZip = $folder.'.zip';

        if (is_file($targetZip)) {
            return;
        }

        $firstDay = date('Y-m-01', strtotime("$thisMonth -1 month"));
        $lastDay = date('Y-m-d', strtotime("$firstDay +1 month -1 day"));

        $root = public_path(CabinetDataSecondBackup::CATALOGUE).'/';

        $days = [];
        $day = $firstDay;
        while (true) {
            if (is_dir($root.$day)) {
                array_push($days, $day);
            }

            $day = date('Y-m-d', strtotime("$day +1 day"));
            
            if ($day > $lastDay) {
                break;
            }
        }

        if (empty($days)) {
            return;
        }

        $zip = $folder.'.zip';
        if (!is_dir($folder)) {
            mkdir($folder);
        }
        chmod($folder, 0777);

        foreach ($days as $oneDay) {
            exec('mv '.$root.$oneDay.' '.$folder);
        }

        $zipper = new Zipper();
        $zipper->make($zip)->folder($folderName)->add($folder)->close();;
        exec('rm -rf '.$folder);
        CabinetDataSecondBackup::whereIn('date', $days)->delete();
        return;
    }
}